<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-11-06
 * Time: 10:41
 */

namespace App\Http\Controllers\Api\Common;

use AlipayNotify;
use AlipayOpenPublicTemplateMessageIndustryModifyRequest;
use App\Http\Controllers\Controller;
use App\Libs\Contracts\PayMent\AliPay\App\aop\AopClient;
use App\Libs\Contracts\PayMent\AliPay\App\aop\request\AlipayFundBatchCreateRequest;
use App\Libs\Contracts\PayMent\AliPay\App\aop\request\AlipayFundTransPagePayRequest;
use App\Libs\httpUtil;
use App\Models\District;
use App\Models\Expressfee;
use App\Models\ExpressfeeCity;
use App\Models\ExpressfeeCityC;
use App\Models\Good;
use App\Models\GoodsStock;
use App\Models\IntegralGood;
use App\Models\IntegrationRecord;
use App\Models\JingangNewGoods;
use App\Models\JinGangOtherGoods;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\OrderReturn;
use App\Models\Supplier;
use App\Models\TeamTask;
use App\Models\User;
use App\Models\UserPriceLog;
use App\Models\UserSaleLog;
use App\Models\UserWithdrawLog;
use App\Services\Ali\AliService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Maatwebsite\Excel\Facades\Excel;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Alipay\EasySDK\Kernel\Config;


class TestController extends Controller
{
    public function test(Request $request)
    {
        \RedisDB::setex("1231", 21600, "3333");

        return var_dump($data);
        $token = new \App\Services\Front\WxService();
        $access_token = $token->getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=$access_token";
        $body = [
            'jump_wxa' => (object)[
                'path' => "pages/home/activityDetail/activityDetail",
                'query' => "id=213"
            ],
            'expire_type' => 1,
            'expire_interval' => 30
        ];
        $http = new httpUtil();
        $data = $http->request($url, $body);
        return var_dump($data);
        if($data['errcode']){
            return $this->apiResponse('', config('errorLiu.SHENGCHENGWAILOAINSHNIB'));
        }
        $url = $data['openlink'];

        return var_dump($url);
//        $goodList = Good::where('image','like',"%https://oss.xmw1688.comhttp://oss.yuncangxiaodian.com%")->get()->toArray();
//        foreach ($goodList as $good) {
//            $image = $good['image'];
//            $image = "https://oss.xmw1688.com".substr($image, 53);
//            Good::where('id', $good['id'])->update(['image' => $image]);
//        }
        return var_dump(21321);
//        $goodStockList = GoodsStock::where('image','not like',"%https://oss.xmw1688.com%")->get()->toArray();
//        foreach ($goodStockList as $goodStock) {
//            $image = $goodStock['image'];
//            if (strstr($image, 'https://oss.yuncangxiaodian.com')) {
//                $image = "https://oss.xmw1688.com".substr($image, 31);
//            }else{
//                if (!strstr($image, 'https://oss.xmw1688.com')) {
//                    $image = "https://oss.xmw1688.com".$image;
//                }
//            }
//            GoodsStock::where('id', $goodStock['id'])->update(['image' => $image]);
//        }
//        $goodList = Good::where('image','not like',"%https://oss.xmw1688.com%")->get()->toArray();
//        foreach ($goodList as $good) {
//            $image = $good['image'];
//            if (strstr($image, 'https://oss.yuncangxiaodian.com')) {
//                $image = "https://oss.xmw1688.com".substr($image, 31);
//            }else{
//                if (!strstr($image, 'https://oss.xmw1688.com')) {
//                    $image = "https://oss.xmw1688.com".$image;
//                }
//            }
//            Good::where('id', $good['id'])->update(['image' => $image]);
//        }
//        $orderDetailList = OrderDetail::where('image','not like',"%https://oss.xmw1688.com%")->get()->toArray();
//        foreach ($orderDetailList as $orderDetail) {
//            $image = $orderDetail['image'];
//            if (strstr($image, 'https://oss.yuncangxiaodian.com')) {
//                $image = "https://oss.xmw1688.com".substr($image, 31);
//            }else{
//                if (!strstr($image, 'https://oss.xmw1688.com')) {
//                    $image = "https://oss.xmw1688.com".$image;
//                }
//            }
//            OrderDetail::where('id', $orderDetail['id'])->update(['image' => $image]);
//        }
        return var_dump(213);
        $supplierList = Supplier::select()->get()->toArray();
        Expressfee::where('id', '!=', 0)->delete();
        ExpressfeeCity::where('id', '!=', 0)->delete();
        ExpressfeeCityC::where('id', '!=', 0)->delete();
        $expressfeeList = [];
        foreach ($supplierList as $key => $supplier) {
            $expressfee = [];
            $expressfee['id'] = $key + 1;
            $expressfee['supplier_id'] = $supplier['id'];
            $expressfee['name'] = "默认模板";
            $expressfeeList[] = $expressfee;
        }
        Expressfee::insert($expressfeeList);
        $districtList = District::where('level', 1)->get()->toArray();
        $expressfeeList = Expressfee::select()->get()->toArray();
        unset($expressfee);
        foreach ($expressfeeList as $expressfee) {
            $expressfeecityCList = [];
            foreach ($districtList as $district) {
                $expressfeecityC = [];
                $expressfeecityC['supplier_id'] = $expressfee['supplier_id'];
                $expressfeecityC['expressfeeid'] = $expressfee['id'];
                $expressfeecityC['area_id'] = $district['district_id'];
                $expressfeecityCList[] = $expressfeecityC;
            }
            ExpressfeeCityC::insert($expressfeecityCList);
            Good::where('supplier_id', $expressfee['supplier_id'])->update(['expressfee_id' => $expressfee['id']]);
            IntegralGood::where('supplier_id', $expressfee['supplier_id'])->update(['expressfee_id' => $expressfee['id']]);
        }
        return var_dump($districtList);
        $test = $request->test;
        // 指明给谁推送，为空表示向所有在线用户推送
        $to_uid = '';
// 推送的url地址，上线时改成自己的服务器地址
        $push_api_url = "http://127.0.0.1:2121/";
        $post_data = array(
            'type' => 'publish',
            'content' => $test,
            'to' => $to_uid,
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $push_api_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
        $return = curl_exec($ch);
        curl_close($ch);
        var_export($return);
        return;
        $month = date("Y-m");
        $time = date("Y-m-d H:i:s");
        $orderReturnList = OrderReturn::where('afterType', 1)->where('isFulfill', 4)->where('isRefundCount', 0)->get()->toArray();
        foreach ($orderReturnList as $value) {
            $orderDetail = OrderDetail::where('orderDetailId', $value['orderDetailId'])->first();
            if ($orderDetail) {
                $userSaleLog = UserSaleLog::where('orderDetailId', $value['orderDetailId'])->where('isRefundCount', 0)->get()->toArray();
                unset($val);
                foreach ($userSaleLog as $val) {
                    if ($val['isInvite']) {
                        $teamTask = TeamTask::where('userId', $val['userId'])->where('createTime', 'like', "%$month%")->first();
                        if ($teamTask) {
                            TeamTask::where('teamTaskId', $teamTask['teamTaskId'])->update([
                                'recedeOrderNum' => \DB::raw('recedeOrderNum + 1'),
                                'recedeOrderPriceNum' => \DB::raw('recedeOrderPriceNum + ' . ($orderDetail['goodNum'] * $orderDetail['price']))
                            ]);
                            UserSaleLog::where('userSaleLogId', $val['userSaleLogId'])->update(['isRefundCount' => 1, 'returnTeamTaskId' => $teamTask['teamTaskId']]);
                        }
                    } else {
                        UserSaleLog::where('userSaleLogId', $val['userSaleLogId'])->update(['isRefundCount' => 1]);
                    }
                }
                $num = UserSaleLog::where('orderDetailId', $value['orderDetailId'])->where('isRefundCount', 0)->count();
                if (!$num) {
                    OrderReturn::where('orderReturnId', $value['orderReturnId'])->update(['isRefundCount' => 1]);
                }
            }
        }
        return var_dump($orderReturnList);
        $http = new httpUtil();
        $accessToken = $http->http_get("https://web-api.rr.tv/web/drama/play?webChannel=M_STATION&dramaId=34896&7-19-0xx", []);
        $accessToken = json_decode($accessToken);
        $url = $accessToken->data->url;
        return var_dump($url);
        $lkt_user_jifen = IntegrationRecord::select('t1.*', 't2.user_name')
            ->from((new IntegrationRecord())->getTable() . ' as t1')
            ->join((new User())->getTable() . ' as t2', 't1.user_id', '=', 't2.user_id')
            ->whereIn('t1.type', [2, 3])
            ->get()->toArray();
        $userList = [];
        foreach ($lkt_user_jifen as $value) {
            if ($value['type'] == 2) {
                if (isset($userList[$value['user_id']])) {
                    $userList[$value['user_id']]['integration_score'] += $value['integration_score'];
                } else {
                    $user = $value;
                    foreach ($lkt_user_jifen as $val) {
                        if ($val['type'] == 3) {
                            if ($user['user_id'] == $val['user_id']) {
                                $user['integration_score'] = $user['integration_score'] - $val['integration_score'];
                            }
                        }
                    }
                    $userList[$user['user_id']]['user_id'] = $user['user_id'];
                    $userList[$user['user_id']]['user_name'] = $user['user_name'];
                    $userList[$user['user_id']]['integration_score'] = $user['integration_score'];
                }
            }
        }
        $i = 0;
        $data[0] = ['用户id', '用户昵称', '未扣除积分'];
        foreach ($userList as $key => &$v) {
            if ($v['integration_score'] > 0) {
                $i += $v['integration_score'];
                $data[] = $v;
            }
        }
        $excelFileName = "积分信息";
        Excel::create($excelFileName, function ($excel) use ($data, $excelFileName) {
            $excel->sheet($excelFileName, function ($sheet) use ($data) {
                $sheet->setFontFamily('宋体');
                $sheet->setAutoSize(true);
                $sheet->rows($data);
            });
        })->store('xls', "/www/wwwroot/laimi_three_server/public/uploads");
        return var_dump($data);


        return var_dump($userList);


        $lkt_user_withdraw_log = UserWithdrawLog::where('auditStatus', "PASS")->get()->toArray();
        $withdrawList = [];
        $withdrawTimeList = [];
        foreach ($lkt_user_withdraw_log as $value) {
            $time = date("Y-m-d", strtotime($value['createTime']));
            if (isset($withdrawList[$time])) {
                $withdrawList[$time] += $value['withdrawPrice'];
            } else {
                $withdrawTimeList[] = $time;
                $withdrawList[$time] = $value['withdrawPrice'];
            }

        }
        unset($value);
        $data = [];
        foreach ($withdrawTimeList as $key => $value) {
            $data[0][] = $value;
            $data[1][] = $withdrawList[$value];
        }
        $excelFileName = "提现信息";
        Excel::create($excelFileName, function ($excel) use ($data, $excelFileName) {
            $excel->sheet($excelFileName, function ($sheet) use ($data) {
                $sheet->setFontFamily('宋体');
                $sheet->setAutoSize(true);
                $sheet->rows($data);
            });
        })->store('xls', "/www/wwwroot/laimi_three_server/public/uploads");
        return var_dump($data);
        $time = date("Y-m-d H:i:s", strtotime("+ 30 Minutes"));
        $arr = $_POST;


        $userWithdrawLogIdList = explode(',', $request->userWithdrawLogIdList);
        $userWithdrawLogList = UserWithdrawLog::whereIn('userWithdrawLogId', $userWithdrawLogIdList)->get()->toArray();
        //return var_dump($userWithdrawLogList);
        if (isset($userWithdrawLogList[0])) {
            $userWithdrawLogList = array_values($userWithdrawLogList);
            $trans_order_list = [];
            foreach ($userWithdrawLogList as $key => $value) {
                $trans_order_list[$key]['out_biz_no'] = $this->build_order_no($value['user_id']);
                $trans_order_list[$key]['trans_amount'] = number_format($value['withdrawPrice'], 2);
                $trans_order_list[$key]['remark'] = date("Y-m-d H:i:s") . "提现打款,用户id：" . $value['user_id'];
                $payee_info = [];
                $payee_info['identity'] = $value['zfbNumber'];
                $payee_info['identity_type'] = "ALIPAY_LOGON_ID";
                $payee_info['name'] = $value['zfbName'];
                $trans_order_list[$key]['payee_info'] = $payee_info;
            }
            $parmArr = [
                "out_batch_no" => $this->build_order_no(),
                "total_trans_amount" => 1.00,
                "total_count" => 1,
                "product_code" => "BATCH_API_TO_ACC",
                "biz_scene" => "MESSAGE_BATCH_PAY",
                "order_title" => "提现打款",
                "remark" => date("Y-m-d H:i:s") . "提现打款",
                "trans_order_list" => $trans_order_list

            ];
            $parmArr = json_encode($parmArr);
            $aop = new AopClient ();
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = env("ALI_APPID");
            $aop->rsaPrivateKey = env("ALI_PAY_PRIVATE_KEY");
            $aop->alipayrsaPublicKey = env("ALI_PAY_PUBLIC_KEY");
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset = 'UTF-8';
            $aop->format = 'json';
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.open.public.template.message.industry.modify
            $request = new AlipayFundBatchCreateRequest();
            $request->setBizContent($parmArr);
            $result = $aop->execute($request);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {
            } else {
                return -1;
            }
            $parmArr = [
                "biz_scene" => "MESSAGE_BATCH_PAY",
                "product_code" => "BATCH_API_TO_ACC",
                "order_id" => $result->$responseNode->batch_trans_id,

            ];
            $parmArr = json_encode($parmArr);
            $request = new AlipayFundTransPagePayRequest();
            $request->setBizContent($parmArr);
            $result = $aop->pageExecute($request);
            return $result;
        }
        return $userWithdrawLogIdList[0];
        $aliService = new AliService();
        Factory::setOptions($aliService->getOptions());
        try {
            //2. 发起API调用（以支付能力下的统一收单交易创建接口为例）
            $result = Factory::payment()->common()->create("iPhone6 16G", "20200326235526001", "88.88", "2088002656718920");
            $responseChecker = new ResponseChecker();
            return var_dump($responseChecker);
            //3. 处理响应或异常
            if ($responseChecker->success($result)) {
                echo "调用成功" . PHP_EOL;
            } else {
                echo "调用失败，原因：" . $result->msg . "，" . $result->subMsg . PHP_EOL;
            }
        } catch (Exception $e) {
            echo "调用失败，" . $e->getMessage() . PHP_EOL;;
        }
        return "12312312tes21321t";


        $public_path = env("WEB_ROOT_URL");
        if (is_dir($public_path)) {
            $handle = opendir($public_path);
            while (($file = readdir($handle)) !== false) {
                if ($file != '.' && $file != '..') {
                    $dir = $public_path . '/' . $file;
                    if (!is_dir($dir)) {
                        unlink($dir);
                    }
                }
            }
            closedir($handle);
        }
        return var_dump(true);


        return "ok";
        $time = date("Y-m-d");
        $bankList = Back::where('isStart', 1)->where('isShow', 0)->where('returnDay', '<=', $time)->get()->toArray();
        $bankIdList = [];
        $saleNoList = [];
        foreach ($bankList as $key => $value) {
            $saleNoList[] = $value['saleNo'];
            $bankIdList[] = $value['backId'];
        }
        Back::whereIn('saleNo', $saleNoList)->update(['isShow' => 0, 'isStart' => 0]);
        Back::whereIn('backId', $bankIdList)->update(['isShow' => 1]);
        return var_dump($bankIdList);


        return "ok";
        $num = 0;
        $n = $request->n;
        $arr = [1, 5, 10, 20, 50];
        $surplus = 100 - $n;
        $price = 0;
        for ($i = 4; $i >= 0; $i--) {
            $numPrcie = intval($surplus / $arr[$i]);
            if ($numPrcie > 0) {
                $num = $num + $numPrcie;
                $surplus = $surplus - ($arr[$i] * $numPrcie);
            }
            if ($surplus == 0) {
                break;
            }
        }

        return $num;
        $status = app('sms')->sendAudit("18636167924", "SMS_201715609", ['name' => "wangchen"]);

        dd($status);

//        $sTime = date("Y-m-d H:i:s",strtotime("-15 minute"));
//        $eTime = date("Y-m-d H:i:s",strtotime("+15 minute"));
//        dd($eTime);
//        CourseCatalog::where('startTime','>=',$sTime)->where('startTime','<=',date("Y-m-d H:i:s"))->where('courseLiveStatus',"UN_LIVE")->where('isWaitLive',0)->update(['isWaitLive'=>1]);
//        CourseCatalog::where('endTime','<=',$eTime)->where('endTime','>=',date("Y-m-d H:i:s"))->whereIn('courseLiveStatus',["LIVED",'REPLAY'])->where('isWaitLive',1)->update(['isWaitLive'=>0]);
//        Activity::where('liveStartTime','<=',date('Y-m-d H:i:s'))
//            ->where('liveStatus',"UNSTART")->where('isLive',1)
//            ->update(['liveStatus'=>'STARTING']);
//        Activity::where('liveEndTime','<=',date('Y-m-d H:i:s'))
//            ->where('liveStatus',"STARTING")->where('isLive',1)
//            ->update(['liveStatus'=>'END']);
//        $incomeList =  Income::whereNull('accountTime')->where('freezeStatus','UN_ACOUNT')->groupBy('orderNo')->get()->toArray();
//        $courseService = new CourseService();
//        foreach ($incomeList as $value){
//            $courseService->addIncomeReal($value);
//        }
//        $pushService = new  PushService();
//        $pushService->pushOne("213213","21321",100725,["pushType"=>"URL","pushTypeId"=>1,'pushContent'=>"www.baidu.com"],'USER');

//        $incomeList =  Income::whereNull('accountTime')->where('freezeStatus','UN_ACOUNT')->groupBy('orderNo')->get()->toArray();
//        $courseService = new CourseService();
//        foreach ($incomeList as $value){
//            $courseService->addIncomeReal($value);
//        }
        $im = new ImController();
        return $im->selectGroup(442681);
//        $videoUrl = "http://xiaofu30days.oss-cn-beijing.aliyuncs.com/nfv2p08m71592643536883.mp4";
//        $arr = explode(";", $videoUrl);
//        if (sizeof($arr) == 1) {
//            $url = $arr[0];
//            $video[1] = $url;
//            $video[0] = $url."?x-oss-process=video/snapshot,t_1000,f_jpg,m_fast";
//            ksort($video);
//            $videoUrl = implode(";",$video);
//        }
//        return $videoUrl;
//        UserExtent::where('userId',100749)->update([
//
//            'incomeBalance' => \DB::raw('incomeBalance + 1'),
//            'withdrawBalance'  => \DB::raw('withdrawBalance + 1'),
//            'distributionBalance'  => \DB::raw('distributionBalance + 1')
//
//        ]);
//        $userId = $request->USERID;
//        $pageSize = $request->pageSize;
//        $exchangeList = ExchangeBatch::select()
//            ->from((new ExchangeBatch())->getTable(). " as t1")
//            ->join((new ExchangeUser())->getTable(). ' as t2' ,'t1.exchangeBatchId','=','t2.exchangeBatchId')
//            ->paginate($pageSize)->toArray();
//        foreach ($exchangeList['data'] as &$v){
//            $v['courseList'] = ExchangeCourse::select('t2.*')
//                ->from((new ExchangeCourse())->getTable(). " as t1")
//                ->join((new Course())->getTable(). ' as t2' ,'t1.courseId','=','t1.courseId')
//                ->where('t1.exchangeBatchId',$v['exchangeBatchId'])->get()->toArray();
//        }
//        dd($exchangeList);
//        $im = new LiveController();
//        $im->sVideoList("325");
        return;
        $fileName = "/service/wxapp/pet/pet_server/public/uploads/语言资源文件-管理后台-200731简化.xlsx";

        if (!file_exists($fileName)) {
            return 404;
        }
        $objPHPExcel = Excel::load($fileName);//获取sheet表格数目
        $objPHPExcel->setActiveSheetIndex(0);

        $rowCount = $objPHPExcel->getActiveSheet()->getHighestRow();//获取表格列数
        $columnCount = $objPHPExcel->getActiveSheet()->getHighestColumn();
        $arr = [];
        for ($row = 2; $row <= $rowCount; $row++) {
//列数循环 , 列数是以A列开始
            $name = $objPHPExcel->getActiveSheet()->getCell("A" . $row)->getValue();

            if ($name != null) {
                $key = $objPHPExcel->getActiveSheet()->getCell('A' . $row)->getValue();
                $value = $objPHPExcel->getActiveSheet()->getCell('C' . $row)->getValue();


                $arr[$key] = $value;
            }

        }
        return $this->apiResponse($arr);

    }

    function getBase64ByImageUrl($url)
    {
        $header = [
            'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
            'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
            'Accept-Encoding: gzip, deflate',
        ];
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_ENCODING, "gzip");
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $data = curl_exec($curl);
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        if ($code == 200) {//把URL格式的图片转成base64_encode格式的！
            $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
            return $imgBase64Code;//图片内容
        } else {
            return "";
        }
    }
}